<template>
  <div class="article-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">article</h1>
        <div class="header-actions">
          <el-button
            type="primary"
            @click="$router.push('/write')"
            v-if="userStore.isLoggedIn"
          >
            <el-icon><Edit /></el-icon>
            write an article
          </el-button>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="filter-left">
          <div class="el-radio-group">
            <label
              class="el-radio-button"
              :class="{ 'is-active': currentSort == '2' }"
            >
              <input
                class="el-radio-button__original-radio"
                type="radio"
                name="article-sort"
                value="2"
                v-model="currentSort"
                @change="handleSortChange"
              />
              <span class="el-radio-button__inner">Latest</span>
            </label>
            <label
              class="el-radio-button"
              :class="{ 'is-active': currentSort == '3' }"
            >
              <input
                class="el-radio-button__original-radio"
                type="radio"
                name="article-sort"
                value="3"
                v-model="currentSort"
                @change="handleSortChange"
              />
              <span class="el-radio-button__inner">Hottest</span>
            </label>
            <label
              class="el-radio-button"
              :class="{ 'is-active': currentSort == '4' }"
            >
              <input
                class="el-radio-button__original-radio"
                type="radio"
                name="article-sort"
                value="4"
                v-model="currentSort"
                @change="handleSortChange"
              />
              <span class="el-radio-button__inner">Most Likes</span>
            </label>
          </div>
        </div>
        <div class="filter-right">
          <el-input
            v-model="searchKeyword"
            placeholder="Search articles..."
            style="width: 300px"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <el-icon class="search-icon" @click="handleSearch">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="article-list" v-loading="loading">
      <div
        v-for="article in articles"
        :key="article.id"
        class="article-item"
        @click="goToArticleDetail(article.id)"
      >
        <div class="article-content">
          <!-- 文章头部信息 -->
          <div class="article-header">
            <div class="author-info">
              <el-avatar :src="getMediaUrl(article.userAvatar)" :size="32">
                {{ article.userNickname?.charAt(0) }}
              </el-avatar>
              <div class="author-details">
                <span class="author-name">{{ article.userNickname }}</span>
                <span class="publish-time">{{
                  formatTime(article.publishTime || article.createdTime)
                }}</span>
              </div>
            </div>
            <div class="article-status" v-if="article.status === 1">
              <el-tag type="info" size="small">草稿</el-tag>
            </div>
          </div>

          <!-- 文章标题 -->
          <h2 class="article-title">{{ article.title }}</h2>

          <!-- 文章摘要 -->
          <p class="article-summary" v-if="article.summary">
            {{ article.summary }}
          </p>

          <!-- 文章封面 -->
          <div class="article-cover" v-if="article.coverImage">
            <img :src="getMediaUrl(article.coverImage)" :alt="article.title" />
          </div>

          <!-- 话题标签 -->
          <div
            class="article-topics"
            v-if="article.topics && article.topics.length > 0"
          >
            <el-tag
              v-for="topic in article.topics"
              :key="topic.id"
              size="small"
              class="topic-tag clickable"
              @click.stop="goToTopicDetail(topic.id)"
            >
              {{ topic.name }}
            </el-tag>
          </div>

          <!-- 文章统计信息 -->
          <div class="article-stats">
            <div class="stats-left">
              <span class="stat-item">
                <el-icon><View /></el-icon>
                {{ formatCount(article.viewCount) }}
              </span>
              <span class="stat-item">
                <el-icon><ChatDotRound /></el-icon>
                {{ formatCount(article.commentCount) }}
              </span>
            </div>
            <div class="stats-right">
              <button
                class="action-btn like-btn"
                :class="{ active: article.isLiked }"
                @click.stop="handleLikeArticle(article.id, article.isLiked)"
              >
                <el-icon><CaretTop /></el-icon>
                <span>{{ formatCount(article.likeCount) }}</span>
              </button>
              <button
                class="action-btn collect-btn"
                :class="{ active: article.isCollected }"
                @click.stop="
                  handleCollectArticle(article.id, article.isCollected)
                "
              >
                <el-icon><Star /></el-icon>
                <span>{{ formatCount(article.collectCount) }}</span>
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div
        v-if="!loading && (!articles || articles.length === 0)"
        class="empty-state"
      >
        <el-empty description="暂无文章">
          <el-button
            type="primary"
            @click="$router.push('/write')"
            v-if="userStore.isLoggedIn"
          >
            写第一篇文章
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  CaretTop,
  ChatDotRound,
  Edit,
  Search,
  Star,
  View,
} from "@element-plus/icons-vue";
import { useUserStore } from "@/stores/user";
import {
  getArticleList,
  toggleCollectArticle,
  toggleLikeArticle,
} from "@/api/article";
import { formatCount, formatTime } from "@/utils/format";
import { getMediaUrl } from "@/utils/media";

const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const articles = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);
const currentSort = ref("2");
const searchKeyword = ref("");

// 生命周期
onMounted(() => {
  loadArticles();
});

// 方法
const loadArticles = async () => {
  loading.value = true;
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      sortType: parseInt(currentSort.value),
      keyword: searchKeyword.value || undefined,
      status: 2,
    };

    const response = await getArticleList(params);
    if (response.code === 200) {
      articles.value = response.data?.data || [];
      total.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.message || "获取文章列表失败");
    }
  } catch (error) {
    console.error("获取文章列表失败:", error);
    ElMessage.error("获取文章列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSortChange = () => {
  currentPage.value = 1;
  loadArticles();
};

const handleSearch = () => {
  currentPage.value = 1;
  loadArticles();
};

const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  loadArticles();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loadArticles();
};

const goToArticleDetail = (articleId) => {
  router.push(`/article/${articleId}`);
};

const goToTopicDetail = (topicId) => {
  router.push(`/topic/${topicId}?tab=articles`);
};

const handleLikeArticle = async (articleId, isLiked) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    const response = await toggleLikeArticle(articleId);
    if (response.code === 200) {
      const article = articles.value.find((a) => a.id === articleId);
      if (article) {
        article.isLiked = !isLiked;
        article.likeCount += article.isLiked ? 1 : -1;
      }
      ElMessage.success(article.isLiked ? "点赞成功" : "已取消点赞");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("点赞操作失败:", error);
    ElMessage.error("操作失败");
  }
};

const handleCollectArticle = async (articleId, isCollected) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning("请先登录");
    return;
  }

  try {
    const response = await toggleCollectArticle(articleId);
    if (response.code === 200) {
      const article = articles.value.find((a) => a.id === articleId);
      if (article) {
        article.isCollected = !isCollected;
        article.collectCount += article.isCollected ? 1 : -1;
      }
      ElMessage.success(article.isCollected ? "收藏成功" : "已取消收藏");
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    ElMessage.error("操作失败");
  }
};
</script>

<style lang="scss" scoped>
.article-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
}

.page-header {
  margin-bottom: 24px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .page-title {
    font-size: 28px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0;
  }
}

.filter-section {
  margin-bottom: 24px;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;

  .filter-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-icon {
    cursor: pointer;
    color: #8590a6;

    &:hover {
      color: $primary-color;
    }
  }
}

.article-list {
  min-height: 400px;
}

.article-item {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 16px;
  border: 1px solid #f0f0f0;
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    border-color: #d9d9d9;
  }
}

.article-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.author-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.author-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.author-name {
  font-weight: 500;
  color: #1a1a1a;
  font-size: 14px;
}

.publish-time {
  font-size: 12px;
  color: #8590a6;
}

.article-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 12px 0;
  line-height: 1.4;

  &:hover {
    color: $primary-color;
  }
}

.article-summary {
  color: #666;
  line-height: 1.6;
  margin: 0 0 16px 0;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.article-cover {
  margin: 16px 0;

  img {
    width: 100%;
    max-height: 200px;
    object-fit: cover;
    border-radius: 6px;
  }
}

.article-topics {
  margin: 16px 0;

  .topic-tag {
    margin-right: 8px;
    margin-bottom: 4px;

    &.clickable {
      cursor: pointer;
      transition: all 0.2s ease;

      &:hover {
        background-color: #e6f7ff;
        border-color: #91d5ff;
        color: #1890ff;
        transform: translateY(-1px);
      }
    }
  }
}

.article-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

.stats-left {
  display: flex;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #8590a6;
  font-size: 14px;
}

.stats-right {
  display: flex;
  gap: 8px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  border: 1px solid #e1e8ed;
  background: white;
  color: #8590a6;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 14px;

  &:hover {
    background: #f7f8fa;
    border-color: #d9d9d9;
  }

  &.active {
    color: #1890ff;
    border-color: #1890ff;
    background: #f0f8ff;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
  padding-top: 24px;
  border-top: 1px solid #f0f0f0;
}
</style>
